package com.arvin.faceDetect.utils

import android.graphics.Bitmap
import android.graphics.Color
import android.util.Log
import kotlin.math.ln
import kotlin.math.max
import kotlin.math.min

object ImageQualityAnalyzer {
    private const val TAG = "ImageQualityAnalyzer"

    // 光照阈值
    private const val MIN_BRIGHTNESS = 0.2f
    private const val MAX_BRIGHTNESS = 0.8f

    // 对比度阈值
    private const val MIN_CONTRAST = 0.3f
    private const val MAX_CONTRAST = 0.7f

    // 直方图均衡化阈值
    private const val HISTOGRAM_THRESHOLD = 0.4f

    fun analyzeImageQuality(bitmap: Bitmap): PreprocessOptions {
        val brightness = calculateBrightness(bitmap)
        val contrast = calculateContrast(bitmap)
        val histogram = calculateHistogram(bitmap)

        Log.d(
            TAG, """
            图像质量分析结果:
            亮度: $brightness
            对比度: $contrast
            直方图分布: ${histogram.contentToString()}
        """.trimIndent()
        )

        return PreprocessOptions(
            needLightingNormalization = brightness < MIN_BRIGHTNESS || brightness > MAX_BRIGHTNESS,
            needContrastEnhancement = contrast < MIN_CONTRAST || contrast > MAX_CONTRAST,
            needHistogramEqualization = shouldEqualizeHistogram(histogram)
        )
    }

    private fun calculateBrightness(bitmap: Bitmap): Float {
        var totalBrightness = 0f
        val width = bitmap.width
        val height = bitmap.height
        val pixels = IntArray(width * height)

        bitmap.getPixels(pixels, 0, width, 0, 0, width, height)

        for (pixel in pixels) {
            val r = Color.red(pixel)
            val g = Color.green(pixel)
            val b = Color.blue(pixel)
            totalBrightness += (r + g + b) / (3f * 255f)
        }

        return totalBrightness / (width * height)
    }

    private fun calculateContrast(bitmap: Bitmap): Float {
        var minBrightness = 1f
        var maxBrightness = 0f
        val width = bitmap.width
        val height = bitmap.height
        val pixels = IntArray(width * height)

        bitmap.getPixels(pixels, 0, width, 0, 0, width, height)

        for (pixel in pixels) {
            val r = Color.red(pixel)
            val g = Color.green(pixel)
            val b = Color.blue(pixel)
            val brightness = (r + g + b) / (3f * 255f)
            minBrightness = min(minBrightness, brightness)
            maxBrightness = max(maxBrightness, brightness)
        }

        return maxBrightness - minBrightness
    }

    private fun calculateHistogram(bitmap: Bitmap): IntArray {
        val histogram = IntArray(256)
        val width = bitmap.width
        val height = bitmap.height
        val pixels = IntArray(width * height)

        bitmap.getPixels(pixels, 0, width, 0, 0, width, height)

        for (pixel in pixels) {
            val r = Color.red(pixel)
            val g = Color.green(pixel)
            val b = Color.blue(pixel)
            val gray = ((r + g + b) / 3).toInt()
            histogram[gray]++
        }

        return histogram
    }

    private fun shouldEqualizeHistogram(histogram: IntArray): Boolean {
        val total = histogram.sum()
        val normalized = histogram.map { it.toFloat() / total }.toFloatArray()

        // 计算直方图的熵
        var entropy = 0f
        for (p in normalized) {
            if (p > 0) {
                entropy -= p * ln(p)
            }
        }

        // 如果熵值小于阈值，说明图像对比度较低，需要均衡化
        return entropy < HISTOGRAM_THRESHOLD
    }

    data class PreprocessOptions(
        val needLightingNormalization: Boolean,
        val needContrastEnhancement: Boolean,
        val needHistogramEqualization: Boolean
    )
} 